"""
生涯概览报告生成器
基于用户购买行为、会员等级、积分记录等数据，生成个性化的生涯概览报告
"""

import json
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
from pathlib import Path
import os

class CareerOverviewAgent:
    """生涯概览报告生成智能体"""
    
    def __init__(self):
        # 数据文件在项目根目录的data文件夹中
        self.data_dir = Path(__file__).parent.parent / "data"
        
    def load_user_data(self, user_email: str) -> Dict[str, Any]:
        """加载用户数据"""
        try:
            # 加载用户基本信息
            users_file = self.data_dir / "users.json"
            if users_file.exists():
                with open(users_file, 'r', encoding='utf-8') as f:
                    users_data = json.load(f)
                    user_info = users_data.get("users", {}).get(user_email, {})
            else:
                user_info = {}
            
            # 加载订单数据
            orders_file = self.data_dir / "orders.json"
            if orders_file.exists():
                with open(orders_file, 'r', encoding='utf-8') as f:
                    orders_data = json.load(f)
                    user_orders = orders_data.get("orders", {}).get(user_email, [])
            else:
                user_orders = []
            
            # 加载积分数据
            points_file = self.data_dir / "user_points.json"
            if points_file.exists():
                with open(points_file, 'r', encoding='utf-8') as f:
                    points_data = json.load(f)
                    user_points = points_data.get(user_email, {"points": 0, "transactions": []})
            else:
                user_points = {"points": 0, "transactions": []}
            
            # 加载会员数据
            membership_file = self.data_dir / "membership.json"
            if membership_file.exists():
                with open(membership_file, 'r', encoding='utf-8') as f:
                    membership_data = json.load(f)
                    user_membership = membership_data.get(user_email, {})
            else:
                user_membership = {}
            
            return {
                "user_info": user_info,
                "orders": user_orders,
                "points": user_points,
                "membership": user_membership
            }
            
        except Exception as e:
            print(f"加载用户数据时出错: {e}")
            return {
                "user_info": {},
                "orders": [],
                "points": {"points": 0, "transactions": []},
                "membership": {}
            }
    
    def analyze_shopping_behavior(self, orders: List[Dict]) -> Dict[str, Any]:
        """分析购物行为"""
        if not orders:
            return {
                "total_orders": 0,
                "total_spent": 0,
                "avg_order_value": 0,
                "favorite_categories": [],
                "shopping_frequency": "新用户",
                "spending_trend": "暂无数据"
            }
        
        total_orders = len(orders)
        total_spent = sum(order.get("total_amount", 0) for order in orders)
        avg_order_value = total_spent / total_orders if total_orders > 0 else 0
        
        # 分析商品类别偏好
        category_count = {}
        for order in orders:
            for item in order.get("items", []):
                category = item.get("category", "其他")
                category_count[category] = category_count.get(category, 0) + 1
        
        favorite_categories = sorted(category_count.items(), key=lambda x: x[1], reverse=True)[:3]
        
        # 分析购物频率
        if total_orders >= 20:
            shopping_frequency = "资深买家"
        elif total_orders >= 10:
            shopping_frequency = "活跃用户"
        elif total_orders >= 5:
            shopping_frequency = "普通用户"
        else:
            shopping_frequency = "新手用户"
        
        # 分析消费趋势
        if total_spent >= 10000:
            spending_trend = "高消费用户"
        elif total_spent >= 5000:
            spending_trend = "中等消费用户"
        elif total_spent >= 1000:
            spending_trend = "一般消费用户"
        else:
            spending_trend = "轻度消费用户"
        
        return {
            "total_orders": total_orders,
            "total_spent": round(total_spent, 2),
            "avg_order_value": round(avg_order_value, 2),
            "favorite_categories": favorite_categories,
            "shopping_frequency": shopping_frequency,
            "spending_trend": spending_trend
        }
    
    def analyze_growth_journey(self, user_data: Dict[str, Any]) -> Dict[str, Any]:
        """分析用户成长历程"""
        user_info = user_data["user_info"]
        membership = user_data["membership"]
        points = user_data["points"]
        
        # 注册时长
        created_at = user_info.get("created_at", "")
        if created_at:
            try:
                join_date = datetime.strptime(created_at, "%Y-%m-%d %H:%M:%S")
                days_since_join = (datetime.now() - join_date).days
            except:
                days_since_join = 0
        else:
            days_since_join = 0
        
        # 会员等级进展
        current_level = membership.get("level", "青铜会员")
        total_points = points.get("points", 0)
        
        # 成长阶段判定
        if days_since_join >= 365:
            growth_stage = "资深会员"
        elif days_since_join >= 180:
            growth_stage = "成熟用户"
        elif days_since_join >= 30:
            growth_stage = "活跃新人"
        else:
            growth_stage = "新注册用户"
        
        return {
            "days_since_join": days_since_join,
            "growth_stage": growth_stage,
            "current_level": current_level,
            "total_points": total_points,
            "join_date": created_at
        }
    
    def generate_insights_and_recommendations(self, user_data: Dict[str, Any], 
                                           shopping_analysis: Dict[str, Any],
                                           growth_analysis: Dict[str, Any]) -> List[str]:
        """生成个性化洞察和建议"""
        insights = []
        
        # 基于购物行为的洞察
        if shopping_analysis["total_orders"] == 0:
            insights.append("🎯 您还没有进行首次购买，建议浏览我们的精选商品开始您的购物之旅！")
        elif shopping_analysis["shopping_frequency"] == "资深买家":
            insights.append("🌟 您是我们的忠实客户！感谢您的长期支持和信任。")
        
        # 基于消费水平的建议
        if shopping_analysis["spending_trend"] == "高消费用户":
            insights.append("💎 您的消费能力很强，建议关注我们的奢侈品专区和限量商品。")
        elif shopping_analysis["spending_trend"] == "轻度消费用户":
            insights.append("💡 建议关注我们的优惠活动和积分兑换，让您的每一分钱都花得更值！")
        
        # 基于商品偏好的推荐
        if shopping_analysis["favorite_categories"]:
            top_category = shopping_analysis["favorite_categories"][0][0]
            insights.append(f"🎁 基于您对{top_category}的偏好，我们会为您推送相关的新品和优惠信息。")
        
        # 基于会员等级的建议
        current_level = growth_analysis["current_level"]
        if current_level == "青铜会员":
            insights.append("📈 继续购物和积累积分，您很快就能升级到白银会员，享受更多折扣！")
        elif current_level in ["黄金会员", "铂金会员", "钻石会员"]:
            insights.append("👑 恭喜您是我们的高级会员！享受专属服务和优先客服支持。")
        
        # 基于积分情况的建议
        total_points = growth_analysis["total_points"]
        if total_points >= 500:
            insights.append("🎯 您的积分余额充足，可以在积分商城兑换心仪的奖品！")
        elif total_points < 100:
            insights.append("📱 建议多参与平台活动，快速积累积分享受更多优惠。")
        
        return insights
    
    def generate_career_overview_report(self, user_email: str) -> Dict[str, Any]:
        """生成完整的生涯概览报告"""
        try:
            # 加载用户数据
            user_data = self.load_user_data(user_email)
            
            # 分析购物行为
            shopping_analysis = self.analyze_shopping_behavior(user_data["orders"])
            
            # 分析成长历程
            growth_analysis = self.analyze_growth_journey(user_data)
            
            # 生成洞察和建议
            insights = self.generate_insights_and_recommendations(
                user_data, shopping_analysis, growth_analysis
            )
            
            # 计算综合评分
            score_factors = [
                min(shopping_analysis["total_orders"] * 2, 30),  # 订单数量 (最高30分)
                min(shopping_analysis["total_spent"] / 100, 25), # 消费金额 (最高25分)
                min(growth_analysis["days_since_join"] / 10, 20), # 注册时长 (最高20分)
                min(growth_analysis["total_points"] / 50, 15),   # 积分数量 (最高15分)
                10 if growth_analysis["current_level"] != "青铜会员" else 5  # 会员等级 (10分)
            ]
            overall_score = min(sum(score_factors), 100)
            
            # 生成报告
            report = {
                "user_email": user_email,
                "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "overall_score": round(overall_score, 1),
                "shopping_analysis": shopping_analysis,
                "growth_analysis": growth_analysis,
                "insights_and_recommendations": insights,
                "summary": {
                    "user_type": shopping_analysis["shopping_frequency"],
                    "spending_level": shopping_analysis["spending_trend"],
                    "growth_stage": growth_analysis["growth_stage"],
                    "membership_level": growth_analysis["current_level"]
                }
            }
            
            return report
            
        except Exception as e:
            # 返回错误报告
            return {
                "user_email": user_email,
                "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "error": f"生成报告时出错: {str(e)}",
                "overall_score": 0,
                "shopping_analysis": {},
                "growth_analysis": {},
                "insights_and_recommendations": ["暂时无法生成个性化报告，请稍后再试。"],
                "summary": {
                    "user_type": "未知",
                    "spending_level": "未知",
                    "growth_stage": "未知", 
                    "membership_level": "未知"
                }
            }

# 创建全局实例
career_agent = CareerOverviewAgent()

def generate_user_career_report(user_email: str) -> Dict[str, Any]:
    """对外接口：生成用户生涯报告"""
    return career_agent.generate_career_overview_report(user_email)
